using System;
using System.IO;
using System.Reflection;
using UnityEngine;

public class InitGame : MonoBehaviour
{
    public bool isLoadAssetBundle = false;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    private static void AfterAssembliesLoaded()
    {
        //固定字符串语言，个别语言字符串传递过程中会被修改为本地字符导致无法正确加载资源
        System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("en-US");

        var logPath = Path.Combine(Application.persistentDataPath, "log.txt");
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            logPath = Path.Combine(Directory.GetCurrentDirectory(), "log.txt");
        if (File.Exists(logPath))
            File.Delete(logPath);
        Application.logMessageReceived += (string condition, string stackTrace, LogType type) =>
        {
            File.AppendAllText(logPath, string.Format("{0}\n{1}\n", condition, stackTrace));
        };
    }

    private async void Awake()
    {
#if UNITY_EDITOR
        ResourceHelper.IsAsync = isLoadAssetBundle;
#endif
        if (ResourceHelper.IsAsync)
        {
#if !UNITY_EDITOR
            await new WebRequest().Donwload();
#endif
        }

        await Loader.LoadHybridCLR();

        GameObject.DontDestroyOnLoad(gameObject);
        Assembly hotUpdate = Loader.GetAssembly("HotUpdate");
        var entryType = hotUpdate?.GetType("Entry");
        if (entryType == null)
        {
            throw new Exception("entry type is null");
        }
        var instance = Activator.CreateInstance(entryType);
        entryType.GetMethod("Start")?.Invoke(instance, null);
    }
}
